<?php

class WeixinModel extends Model
{
    private function getAccessToken() //获取access_token
    {
        $appId = 'wx0adbc93d7ad8752d';
        $key = '014b2de491f511074ff6b8ef2185b6f8';
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $key;
        $data = $this->getCurl($url);//通过自定义函数getCurl得到https的内容
        $resultArr = json_decode($data, true);//转为数组
        return $resultArr["access_token"];//获取access_token
    }

    public function getMenu()
    {
        $accessToken = $this->getAccessToken();//获取access_token
        $menuGeUrl = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $accessToken;//POST的url
        $menu = $this->getCurl($menuGeUrl);//将菜单结构体POST给微信服务器

        return ($menu);
    }

    public function creatMenu($data = array(), $id = 0)//创建菜单
    {
        $isUpdateTop = false;
        $new_menu = '{}';
        $old_menu = $this->getMenu();
        $old_menu_array = json_decode($old_menu, true);
        if (empty($data)) {
            return false;
        }
        if (is_array($old_menu_array) && $old_menu_array['errcode'] != '46003') {
            $new_button = [];
            if (isset($old_menu_array['menu']['button']) && $old_menu_array['menu']['button'][0]) {
                //是编辑情况下
                if ($id > 0) {
                    $menuIndex = $this->addIndex($old_menu_array['menu']['button']);
                    foreach ($menuIndex as $k => $v) {
                        $sub_button = [];
                        if (is_array($v['sub_button']) && count($v['sub_button']) > 0) {
                            foreach ($v['sub_button'] as $key => $val) {
                                if ($val['id'] == $id) {
                                    //如果是更换了上级菜单目录，则把该条记录删除
                                    if ($data['top_menu_name'] != $v['name']) {
                                        unset($old_menu_array['menu']['button'][$k]['sub_button'][$key]);
                                        $isUpdateTop = true;
                                        break;
                                    } else {
                                        $old_menu_array['menu']['button'][$k]['sub_button'][$key] = ['name' => $data['menu_name'], 'type' => $data['menu_type'], 'url' => $data['menu_url'], 'sub_button' => []];
                                    }
                                }
                                $sub_button[] = $old_menu_array['menu']['button'][$k]['sub_button'][$key];
                            }
                        }
                        if ($v['id'] == $id) {
                            if ($data['top_menu_name'] != '0') {
                                //如果变更一级菜单，则删除
                                unset($old_menu_array['menu']['button'][$k]);
                                $isUpdateTop = true;
                                break;
                            } else {
                                $old_menu_array['menu']['button'][$k] = ['name' => $data['menu_name'], 'type' => $data['menu_type'], 'url' => $data['menu_url'], 'sub_button' => $sub_button];
                            }
                        }
                    }
                    array_values($old_menu_array['menu']['button']);
                    if (!$isUpdateTop) {
                        $new_button['button'] = $old_menu_array['menu']['button'];
                        $new_menu = json_encode($new_button, JSON_UNESCAPED_UNICODE);
                    }
                }
                if ($id == 0 || $isUpdateTop) {
                    if ($data['top_menu_name'] == '0') {
                        $old_button_array = $old_menu_array['menu']['button'];
                        if (count($old_button_array) >= 3) {
                            $return = [
                                'errmsg' => '最多包括3个一级菜单',
                                'errcode' => 999
                            ];
                            return json_encode($return);
                        }
                        $old_button_array[] = ['name' => $data['menu_name'], 'type' => $data['menu_type'], 'url' => $data['menu_url'], 'sub_button' => []];
                        $new_button['button'] = $old_button_array;
                        $new_menu = json_encode($new_button, JSON_UNESCAPED_UNICODE);
                    } else {
                        //添加现有一级菜单下的二级菜单
                        foreach ($old_menu_array['menu']['button'] as $k => $old_one_button) {
                            if ($old_one_button['name'] == $data['top_menu_name']) {
                                if(count($old_one_button['sub_button']>=5)){
                                    $return = [
                                        'errmsg' => '每个一级菜单最多包含5个二级菜单',
                                        'errcode' => 999
                                    ];
                                    return json_encode($return);
                                }
                                $old_menu_array['menu']['button'][$k]['sub_button'][] = ['name' => $data['menu_name'], 'type' => $data['menu_type'], 'url' => $data['menu_url'], 'sub_button' => []];
                            }
                        }
                        $new_button = $old_menu_array['menu'];
                        $new_menu = json_encode($new_button, JSON_UNESCAPED_UNICODE);
                    }
                }
            }
        } else {
            //添加第一个按钮
            if ($data['top_menu_name'] == '0') {
                $old_button_array[] = ['name' => $data['menu_name'], 'type' => $data['menu_type'], 'url' => $data['menu_url'], 'sub_button' => []];
                $new_button['button'] = $old_button_array;
                $new_menu = json_encode($new_button, JSON_UNESCAPED_UNICODE);
            } else {
                //应该不会有这种情况，先测试下吧
                foreach ($old_menu_array['menu']['button'] as $k => $old_one_button) {
                    if ($old_one_button['name'] == $data['top_menu_name']) {
                        $old_menu_array['menu']['button'][$k]['sub_button'][] = ['name' => $data['menu_name'], 'type' => $data['menu_type'], 'url' => $data['menu_url'], 'sub_button' => []];
                    }
                }
                $new_button = $old_menu_array['menu'];
                $new_menu = json_encode($new_button, JSON_UNESCAPED_UNICODE);
            }
        }

        $accessToken = $this->getAccessToken();//获取access_token invalid charset.   invalid button size rid: 5fed7fd2-11200ca3-2575d7d4
        $menuPostString = '{
                "button": [
                    {
                        "name": "我时尚圈", 
                        "sub_button": [
                            {
                                "type": "view", 
                                "name": "时尚圈", 
                                "url": "http://circle.geekwonderland.net/", 
                                "key": "V1001_TODAY_MUSIC", 
                                "sub_button": [ ]
                            }
                        ]
                    }
                ]
            }';
        $menuPostUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $accessToken;//POST的url
        $menu = $this->dataPost($new_menu, $menuPostUrl);//将菜单结构体POST给微信服务器
        return ($menu);
    }


    public function deleteallmenu()
    {
        $accessToken = $this->getAccessToken();//获取access_token
        $menuPostUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" . $accessToken;//POST的url
        $menu = $this->getCurl($menuPostUrl);//将菜单结构体POST给微信服务器
        return ($menu);
    }

    function getCurl($url)
    {//get https的内容
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不输出内容
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    function dataPost($post_string, $url)
    {//POST方式提交数据
        $context = array('http' => array('method' => "POST", 'header' => "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */*", 'content' => $post_string));
        $stream_context = stream_context_create($context);
        $data = file_get_contents($url, FALSE, $stream_context);
        return $data;
    }

    public function addIndex($button, $index = 0, $return = array())
    {
        foreach ($button as $v) {
            $index++;
            $re = [];
            $id = $index;
            if (is_array($v['sub_button']) && count($v['sub_button']) > 0) {
                foreach ($v['sub_button'] as $val) {
                    $index++;
                    $re[] = ['id' => $index, 'name' => $val['name'], 'sub_button' => $val['sub_button'], 'option' => '<a href="' . U('admin/Config/addmenu', array('tabHash' => 'editmenu', 'id' => $index)) . '">编辑</a>', 'url' => $val['url']];
                }
            }
            $return[] = ['id' => $id, 'name' => $v['name'], 'sub_button' => $re, 'option' => '<a href="' . U('admin/Config/addmenu', array('tabHash' => 'editmenu', 'id' => $id)) . '">编辑</a>', 'url' => $v['url']];
        }
        return $return;
    }
}